//
//  CollageManager.m
//  xiaoyuanshenghuoquan
//
//  Created by Fenrir on 13-11-13.
//  Copyright (c) 2013年 mypocketbaby.com. All rights reserved.
//

#import "CollageManager.h"
#import "Collage.h"
#import "DBKit.h"
#import "FMResultSet.h"
#import "FMDatabaseQueue.h"
#import "FMDatabase.h"

@implementation CollageManager
{

}
- (id)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

+ (NSMutableArray *)collagesWithRegion:(NSString *)region
{
    NSMutableArray *collagesArray = [NSMutableArray new];
    
    NSString *sql = [NSString stringWithFormat:@"select * from collages where region='%@'", region];
    
    FMResultSet* rs = [[DBKit sharedDBKit] querySQL:sql];
    
    while ([rs next]) {
        
        Collage *collage = [Collage new];
        collage.collageId = [rs intForColumn:@"collageId"];
        collage.name = [rs stringForColumn:@"name"];
        collage.region = [rs stringForColumn:@"region"];
        collage.status = NO;
        [collagesArray addObject:collage];
    }
    
    return collagesArray;
}

+ (NSMutableArray *)regions
{
    NSMutableArray *regionsArray = [NSMutableArray new];
    
    NSString *sql = @"select distinct region from collages";
    
    FMResultSet* rs = [[DBKit sharedDBKit] querySQL:sql];
    
    while ([rs next]) {
        
        NSString *region = [rs stringForColumn:@"region"];
        
        [regionsArray addObject:region];
    }
    
    return regionsArray;
}

+ (void)clear
{
    [[DBKit sharedDBKit] truncateCollageTable];
}

+ (BOOL)persistCollages:(NSMutableArray *)collages
{
    //临时封装事务处理
    FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:_SYS_STORAGE_URL];
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        for (Collage *collage in collages) {
            if (![db executeUpdate:[NSString stringWithFormat:@"INSERT INTO collages (collageId,name,region) VALUES('%d','%@','%@')",collage.collageId, collage.name,collage.region]])
            {
                *rollback = YES;
                return;
            }
        }
    }];
    [queue close];
    return YES;
}

@end
